package com.example.administrator.yanfoxconn.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TimePicker;

import com.bumptech.glide.Glide;
import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.adapter.SanFangListAdapter;
import com.example.administrator.yanfoxconn.bean.ActivityMsg;
import com.example.administrator.yanfoxconn.bean.JVSchoolInfo;
import com.example.administrator.yanfoxconn.bean.SelectModel;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.constant.FoxContext;
import com.example.administrator.yanfoxconn.constant.ImageCaptureManager;
import com.example.administrator.yanfoxconn.intent.PhotoPickerIntent;
import com.example.administrator.yanfoxconn.intent.PhotoPreviewIntent;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.DateTimePickDialogUtil;
import com.example.administrator.yanfoxconn.utils.FileUtil;
import com.example.administrator.yanfoxconn.utils.HttpConnectionUtil;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.ImageZipUtils;
import com.example.administrator.yanfoxconn.utils.TimeDateUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.json.JSONArray;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 人資校企合作  服務記錄維護
 * Created by S1007989 on 2021/7/31.
 */

public class SchoolPhotoActivity extends BaseActivity implements View.OnClickListener, DatePicker.OnDateChangedListener, TimePicker.OnTimeChangedListener {
    private final int MESSAGE_SET_TEXT = 1;//掃描成功賦值
    private final int MESSAGE_SET_SCHOOL = 6;//賦值學校
    private final int MESSAGE_TOAST = 2;//掃描失敗彈出框
    private final int MESSAGE_UP = 3;//提交信息回復
    private final int MESSAGE_NETMISTAKE = 5;//網絡錯誤
    private final int MESSAGE_SET_ZN = 7;//ZN：職能
    private final int MESSAGE_SET_DD = 8;//DD：服務地點
    private final int MESSAGE_SET_FW = 9;//FW：服務事項

    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    @BindView(R.id.tv_title)
    TextView tvTittle;//標題
    @BindView(R.id.btn_title_right)
    Button btnUp;//結束/提交

    @BindView(R.id.tv_s_name)
    TextView tvSName;//院校名称
    @BindView(R.id.sp_use)
    Spinner spUse;//人资职能
    @BindView(R.id.tv_date)
    TextView tvDate;//服务日期
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;//開始時間
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;//結束時間
    @BindView(R.id.sp_area)
    Spinner spArea;//服务地点
    @BindView(R.id.sp_way)
    Spinner spWay;//服务事项
    @BindView(R.id.et_man)
    EditText etMan;//男
    @BindView(R.id.et_woman)
    EditText etWoman;//女
    @BindView(R.id.tv_people_num)
    TextView tvPeopleNum;//總數
    @BindView(R.id.et_service_sum)
    EditText etServiceSum;//服务总结
    @BindView(R.id.et_reason)
    EditText et_reason;//備註

    @BindView(R.id.iv_empty1)
    ImageView ivEmptyOne;//空白图片占位
    @BindView(R.id.gv_photo1)
    GridView gridViewOne;//图片显示区域

    private static final int REQUEST_CAMERA_CODE_ONE = 111;
    private static final int REQUEST_PREVIEW_CODE_ONE = 221;
    private ArrayList<String> imagePathsOne = null;//圖片未壓縮地址
    private ArrayList<String> imgZipPathsOne = new ArrayList<String>();//圖片壓縮后地址
    private ArrayList<String> imagePathsTwo = null;//圖片未壓縮地址
    private ImageCaptureManager captureManager; // 相机拍照处理类
    private GridAdapter gridAdapterOne;

    private String initStartDateTime; // 初始化开始时间
    private Date curDate = null;//當前時間
    private String curDates;//當前時間
    private SimpleDateFormat formatter;
    private SchoolPhotoActivity mContext = this;
    private boolean b = true;
    private boolean isClicked = true;//判斷是否點擊
    private ActivityMsg activityMsg;

    private JVSchoolInfo schoolInfo;
    private List<JVSchoolInfo> znList,ddList,fwList;
    private String zn,dd,fw,man,woman;
    @Override
    protected void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_school_photo);
        ButterKnife.bind(this);

        //getMessage();//根據工號獲得信息

        tvTittle.setText("服務記錄維護");
        btnUp.setText("提交");
        btnUp.setVisibility(View.VISIBLE);
        btnUp.setOnClickListener(this);
        btnBack.setOnClickListener(this);
        ivEmptyOne.setOnClickListener(this);
        tvDate.setOnClickListener(this);
        tvStartTime.setOnClickListener(this);
        tvEndTime.setOnClickListener(this);

        schoolInfo = (JVSchoolInfo) getIntent().getSerializableExtra("info");
        tvSName.setText(schoolInfo.getSCHOOL_NAME());
        etMan.setText(schoolInfo.getP_COUNT_MAN());
        man=schoolInfo.getP_COUNT_MAN();
        woman=schoolInfo.getP_COUNT_WOMAN();
        etWoman.setText(schoolInfo.getP_COUNT_WOMAN());
        tvPeopleNum.setText(""+(Integer.parseInt(schoolInfo.getP_COUNT_MAN())+Integer.parseInt(schoolInfo.getP_COUNT_WOMAN())));
        etMan.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                man = etMan.getText().toString();
                if (man.equals("")){
                    man="0";
                }
                tvPeopleNum.setText((Integer.parseInt(man)+Integer.parseInt(woman))+"");
            }
            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
        etWoman.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                woman = etWoman.getText().toString();
                if (woman.equals("")){
                    woman="0";
                }
                tvPeopleNum.setText((Integer.parseInt(man)+
                        Integer.parseInt(woman))+"");
            }
            @Override
            public void afterTextChanged(Editable editable) {
            }
        });

        //Log.e("-----activityMsg.getAct_id()-----", activityMsg.getAct_id() );
        formatter = new SimpleDateFormat("HH:mm");
        SimpleDateFormat formatterUse = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        curDate = new Date(System.currentTimeMillis());
        //获取当前时间
        initStartDateTime = formatterUse.format(curDate);
        curDates = formatter.format(curDate);
        date = new StringBuffer();
        time = new StringBuffer();
        initDateTime();
        getInfo("ZN");
        int cols = getResources().getDisplayMetrics().widthPixels / getResources().getDisplayMetrics().densityDpi;
        cols = cols < 4 ? 4 : cols;
        gridViewOne.setNumColumns(cols);

        // preview
        gridViewOne.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == imagePathsOne.size()) {
                    PhotoPickerIntent intent = new PhotoPickerIntent(SchoolPhotoActivity.this);
                    intent.setSelectModel(SelectModel.MULTI);
                    intent.setShowCarema(true); // 是否显示拍照
                    intent.setMaxTotal(9); // 最多选择照片数量，默认为3
                    intent.setSelectedPaths(imagePathsOne); // 已选中的照片地址， 用于回显选中状态

                    startActivityForResult(intent, REQUEST_CAMERA_CODE_ONE);
                } else {
                    PhotoPreviewIntent intent = new PhotoPreviewIntent(SchoolPhotoActivity.this);
                    intent.setCurrentItem(position);
                    intent.setPhotoPaths(imagePathsOne);
                    startActivityForResult(intent, REQUEST_PREVIEW_CODE_ONE);
                }
            }
        });
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_title_left://返回
                finish();
                break;
            case R.id.btn_title_right://提交
                check();
                break;
            case R.id.tv_start_time:
                showTime("s");
               break;
            case R.id.tv_end_time:
                showTime("e");
                break;
            case R.id.iv_empty1:
                PhotoPickerIntent intent = new PhotoPickerIntent(mContext);
                intent.setSelectModel(SelectModel.MULTI);
                intent.setShowCarema(true); // 是否显示拍照
                intent.setMaxTotal(9); // 最多选择照片数量，默认为3
                intent.setSelectedPaths(imagePathsOne); // 已选中的照片地址， 用于回显选中状态

                startActivityForResult(intent, REQUEST_CAMERA_CODE_ONE);
                break;
            case R.id.tv_date:
                showDate();
                break;
        }
    }

    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case Constants.MESSAGE_TOAST://Toast彈出

                   ToastUtils.showLong(SchoolPhotoActivity.this, msg.obj.toString());
//                    finish();
                    break;
                case Constants.MESSAGE_SET_TEXT://text賦值
                    //setText();
//                    aboutAlert(msg.obj.toString(),MESSAGE_SET_TEXT);
                    break;
                case Constants.MESSAGE_UP://提交響應
                    worningAlert(msg.obj.toString(),Constants.MESSAGE_TOAST);
//                    ToastUtils.showLong(CrossScanActivity.this, msg.obj.toString());

                    break;
                case Constants.MESSAGE_ALERT://提交響應
                    worningAlert(msg.obj.toString(),Constants.MESSAGE_TOAST);
//                    ToastUtils.showLong(CrossScanActivity.this, msg.obj.toString());

                    break;
                case MESSAGE_SET_ZN:
                    setZN();
                    getInfo("DD");
                    break;
                case MESSAGE_SET_DD:
                    setDD();
                    getInfo("FW");
                    break;
                case MESSAGE_SET_FW:
                    setFW();
                    break;
            }
            super.handleMessage(msg);
        }
    };

    //提交前檢查
    private void check(){
        if(FoxContext.getInstance().getLoginId().equals("")){
            ToastUtils.showLong(mContext,"登錄超時,請退出重新登錄!");
            return;
        }
        if (etServiceSum.getText().toString().equals("")){
            ToastUtils.showShort(mContext,"請輸入服務總結！");
            return;
        }
        if (tvDate.getText().toString().equals("")||tvEndTime.getText().toString().equals("")||tvStartTime.getText().toString().equals("")) {
            ToastUtils.showShort(mContext,"請检查服務日期時間！");
            return;
        }
        if (TimeDateUtils.hoursDeviationTime(tvStartTime.getText().toString(),tvEndTime.getText().toString())<=0){
            Log.e("-------","hoursDeviationTime=="+TimeDateUtils.hoursDeviationTime(tvStartTime.getText().toString(),tvEndTime.getText().toString()));
            ToastUtils.showShort(mContext,"請检查服務時間！");
            return;
        }
        if (imagePathsOne==null) {
            ToastUtils.showShort(this, "請上傳服務照片");
            return;
        }
        upMsessage();
    }

    //提交信息
    private void upMsessage() {

        final String url = Constants.HTTP_RZXQ_FLOW_OK; //此處寫上自己的URL

        JsonObject object = new JsonObject();

        JsonArray photoArray1 = new JsonArray();

        if (imagePathsOne != null) {
            for (int i = 0; i < imagePathsOne.size(); i++) {
                File pictureFile = new File(imagePathsOne.get(i)); //通過路徑獲取檔
                final String pic_path = imagePathsOne.get(i);
                String sign_dir = Environment.getExternalStorageDirectory() + File.separator + "YanFoxconn" + File.separator + "Photos";
                String _path =  sign_dir + File.separator  + System.currentTimeMillis() +i+ ".jpg";
                final String compressImage = ImageZipUtils.compressImage(pic_path, _path, 80);
                String picBase64Code = ImageZipUtils.imageToBase64(compressImage);
                JsonObject jsonObject1 = new JsonObject();
                jsonObject1.addProperty("file", picBase64Code);
                photoArray1.add(jsonObject1);
            }
            object.add("photo", photoArray1);
        }

        object.addProperty("s_no",schoolInfo.getS_NO());
        object.addProperty("duty_type",zn);
        object.addProperty("service_add",dd);
        object.addProperty("service_content",fw);
        object.addProperty("service_date",tvDate.getText().toString());
        object.addProperty("service_time",tvStartTime.getText().toString()+"-"+tvEndTime.getText().toString());
        object.addProperty("actual_count_m",etMan.getText().toString());
        object.addProperty("actual_count_f", etWoman.getText().toString());
        object.addProperty("service_summary",etServiceSum.getText().toString());
        object.addProperty("remark",et_reason.getText().toString());
        object.addProperty("creator",FoxContext.getInstance().getName());

        Log.e("----object----",  object.toString());

        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                //把网络访问的代码放在这里
                try {
                    showDialog();
                    Log.e("-----url----",  url);
                    String result = HttpConnectionUtil.doPostJsonObject(url, object);
                    if (result != null) {
                        dismissDialog();
                        Log.e("----result-----",  result);
                        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                        String errCode = jsonObject.get("errCode").getAsString();
                        if (errCode.equals("200")) {
                            Message message = new Message();
                            message.what = Constants.MESSAGE_ALERT;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);

                        } else{
                            Message message = new Message();
                            message.what = Constants.MESSAGE_ALERT;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);
                        }
                    }else{
                        Message message = new Message();
                        message.what = Constants.MESSAGE_NETMISTAKE;
                        mHandler.sendMessage(message);
                        finish();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    FileUtil.deletePhotos(mContext);
                }
            }
        }.start();
    }

    //基本信息下拉   傳值：flag ZN：職能     DD：服務地點       FW：服務事項
    private void getInfo(String flag){
        new Thread() {
            @Override
            public void run() {
                String url2 = Constants.HTTP_RZXQ_GET_INFO + "?flag=" + flag;

                Log.e("---------", "url2==fff===" + url2);
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url2);
                dismissDialog();
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                       if (flag.equals("ZN")){
                           znList = new ArrayList<JVSchoolInfo>();

                           for (JsonElement type : array) {
                               JVSchoolInfo humi = gson.fromJson(type, JVSchoolInfo.class);
                               znList.add(humi);
                           }
                           Message message = new Message();
                           message.what = MESSAGE_SET_ZN;
                           message.obj = jsonObject.get("errMessage").getAsString();
                           mHandler.sendMessage(message);
                       }else if (flag.equals("DD")){
                           ddList = new ArrayList<JVSchoolInfo>();

                           for (JsonElement type : array) {
                               JVSchoolInfo humi = gson.fromJson(type, JVSchoolInfo.class);
                               ddList.add(humi);
                           }
                           Message message = new Message();
                           message.what = MESSAGE_SET_DD;
                           message.obj = jsonObject.get("errMessage").getAsString();
                           mHandler.sendMessage(message);
                       }else if (flag.equals("FW")){
                           fwList = new ArrayList<JVSchoolInfo>();

                           for (JsonElement type : array) {
                               JVSchoolInfo humi = gson.fromJson(type, JVSchoolInfo.class);
                               fwList.add(humi);
                           }
                           Message message = new Message();
                           message.what = MESSAGE_SET_FW;
                           message.obj = jsonObject.get("errMessage").getAsString();
                           mHandler.sendMessage(message);
                       }
                    }
                } else {
                    Message message = new Message();
                    message.what = MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    finish();
                }
            }
        }.start();
    }
    private void setZN(){
        List<String> znName=new ArrayList<>();
        for (int i = 0;i<znList.size();i++){
            znName.add(znList.get(i).getNAME());
        }
        //稽核課隊下拉列表選擇
        spUse.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, znName));
        spUse.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String str = znName.get(position);
                zn=znName.get(position);
                Log.e("---------", "最喜欢的水果是：" + str);
//            paramMap.put("kedui",str);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }
    private void setDD(){
        List<String> ddName=new ArrayList<>();
        for (int i = 0;i<ddList.size();i++){
            ddName.add(ddList.get(i).getNAME());
        }
        //稽核課隊下拉列表選擇
        spArea.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ddName));
        spArea.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String str = ddName.get(position);
                dd=ddName.get(position);
                Log.e("---------", "最喜欢的水果是：" + str);
//            paramMap.put("kedui",str);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }
    private void setFW(){
        List<String> fwName=new ArrayList<>();
        for (int i = 0;i<fwList.size();i++){
            fwName.add(fwList.get(i).getNAME());
        }
        //稽核課隊下拉列表選擇
        spWay.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fwName));
        spWay.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String str = fwName.get(position);
                fw=fwName.get(position);
                Log.e("---------", "最喜欢的水果是：" + str);
//            paramMap.put("kedui",str);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }
    //照片上傳 返回
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            switch (requestCode) {
                // 选择照片
                case REQUEST_CAMERA_CODE_ONE:
                    loadAdpater(data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT), requestCode);
                    break;
                // 预览
                case REQUEST_PREVIEW_CODE_ONE:
                    loadAdpater(data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT), requestCode);
                    break;
                // 调用相机拍照
                case ImageCaptureManager.REQUEST_TAKE_PHOTO:
                    if (captureManager.getCurrentPhotoPath() != null) {
                        captureManager.galleryAddPic();

                        ArrayList<String> paths = new ArrayList<>();
                        paths.add(captureManager.getCurrentPhotoPath());
                        loadAdpater(paths, requestCode);
                        Log.e("==========", paths.get(1));
                    }
                    break;
            }
        }
    }

    private void loadAdpater(ArrayList<String> paths, int code) {
        switch (code) {
            case REQUEST_CAMERA_CODE_ONE:
                loadOne(paths);
                break;
            case REQUEST_PREVIEW_CODE_ONE:
                loadOne(paths);
                break;
        }
    }

    private void loadOne(ArrayList<String> paths) {
        if (imagePathsOne == null) {
            imagePathsOne = new ArrayList<>();
        }
        imagePathsOne.clear();
        imagePathsOne.addAll(paths);

        if (paths.size() > 0) {
            ivEmptyOne.setVisibility(View.GONE);
        } else {
            ivEmptyOne.setVisibility(View.VISIBLE);
        }

        try {
            JSONArray obj = new JSONArray(imagePathsOne);
            Log.e("--", obj.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (gridAdapterOne == null) {
            gridAdapterOne = new GridAdapter(imagePathsOne);
            gridViewOne.setAdapter(gridAdapterOne);
            Log.e("----------------", "ddd==" + imagePathsOne.size());
        } else {
            gridAdapterOne.notifyDataSetChanged();
        }
    }

    private void aboutAlert(String msg, final int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("確認信息")
                .setMessage(msg)
                .setCancelable(false)
                .setPositiveButton("確認", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
                        if (type==Constants.MESSAGE_TOAST){
                            finish();
                        }else if(type==Constants.MESSAGE_UP){
                            check();
                        }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
//                        if (type==MESSAGE_TOAST){
//                            finish();
//                        }else if(type==MESSAGE_UP){
//                            check();
//                        }
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }
    private void worningAlert(String msg, final int t) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示信息")
                .setMessage(msg)
                .setCancelable(false)
                .setPositiveButton("確認", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
                        if (t==Constants.MESSAGE_TOAST) {
                            finish();
                        }
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }



    private class GridAdapter extends BaseAdapter {
        private ArrayList<String> listUrls;

        public GridAdapter(ArrayList<String> listUrls) {
            this.listUrls = listUrls;
        }

        @Override
        public int getCount() {
            if (listUrls.size() == 9) {
                return 9;
            } else {
                return listUrls.size() + 1;
            }

        }

        @Override
        public String getItem(int position) {
            return listUrls.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.item_image, null);
                imageView = (ImageView) convertView.findViewById(R.id.imageView);
                convertView.setTag(imageView);
                // 重置ImageView宽高
//                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(columnWidth, columnWidth);
//                imageView.setLayoutParams(params);
            } else {
                imageView = (ImageView) convertView.getTag();
            }

            if (position == listUrls.size()) {
                imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.icon_addpic_unfocused));
                if (position == 9) {
                    imageView.setVisibility(View.GONE);
                }
            } else {
                Glide.with(mContext)
                        .load(new File(getItem(position)))
                        .placeholder(R.mipmap.default_error)
                        .error(R.mipmap.default_error)
                        .centerCrop()
                        .crossFade()
                        .into(imageView);
            }
            return convertView;
        }
    }

    private int year, month, day, hour, minute;
    private void initDateTime() {
        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH) + 1;
        day = calendar.get(Calendar.DAY_OF_MONTH);
        hour = calendar.get(Calendar.HOUR);
        minute = calendar.get(Calendar.MINUTE);
    }
    private StringBuffer date, time;
    private void showDate(){
        AlertDialog.Builder builder = new AlertDialog.Builder(SchoolPhotoActivity.this);
        builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (date.length() > 0) { //清除上次记录的日期
                    date.delete(0, date.length());
                }
                    tvDate.setText(date.append(String.valueOf(year)).append("-").append(String.valueOf(month + 1)).append("-").append(day));
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        final AlertDialog dialog = builder.create();
        View dialogView = View.inflate(SchoolPhotoActivity.this, R.layout.dialog_date, null);
        final DatePicker datePicker = (DatePicker) dialogView.findViewById(R.id.datePicker);
        dialog.setTitle("设置日期");
        dialog.setView(dialogView);
        dialog.show();
        //初始化日期监听事件
        datePicker.init(year, month , day, this);
    }
    private void showTime(String from){
        AlertDialog.Builder builder2 = new AlertDialog.Builder(SchoolPhotoActivity.this);
        builder2.setPositiveButton("设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (time.length() > 0) { //清除上次记录的日期
                    time.delete(0, time.length());
                }
                if (from.equals("s")){
                    tvStartTime.setText(time.append(String.valueOf(hour)).append(":").append(String.valueOf(minute)));
                }else {
                    tvEndTime.setText(time.append(String.valueOf(hour)).append(":").append(String.valueOf(minute)));
                }
                dialog.dismiss();
            }
        });
        builder2.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertDialog dialog2 = builder2.create();
        View dialogView2 = View.inflate(SchoolPhotoActivity.this, R.layout.dialog_time, null);
        TimePicker timePicker = (TimePicker) dialogView2.findViewById(R.id.timePicker);
        timePicker.setCurrentHour(hour);
        timePicker.setCurrentMinute(minute);
        timePicker.setIs24HourView(true); //设置24小时制
        timePicker.setOnTimeChangedListener(this);
        dialog2.setTitle("设置时间");
        dialog2.setView(dialogView2);
        dialog2.show();
    }
    @Override
    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        this.year = year;
        this.month = monthOfYear;
        this.day = dayOfMonth;
    }
    @Override
    public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
            this.hour = hourOfDay;
            this.minute = minute;
    }
}
